<template>
  <div class="statistics-cards">
    <el-row v-loading="loading" :gutter="24">
      <!-- 总敏感词数 -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card total" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics?.totalWords || 0 }}</div>
              <div class="stat-label">总敏感词数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 启用的敏感词数 -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card enabled" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics?.enabledWords || 0 }}</div>
              <div class="stat-label">启用中</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 禁用的敏感词数 -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card disabled" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">
                {{ statistics?.disabledWords || 0 }}
              </div>
              <div class="stat-label">已禁用</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 今日新增 -->
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card today" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Plus /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics?.todayAdded || 0 }}</div>
              <div class="stat-label">今日新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细统计 -->
    <el-row :gutter="24" style="margin-top: 24px">
      <!-- 类型分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <h4>类型分布</h4>
              <el-button size="small" @click="refreshTypeChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="type-statistics">
            <div
              v-for="(count, type) in typeDistribution"
              :key="type"
              class="type-item"
            >
              <div class="type-info">
                <el-tag
                  :style="{
                    backgroundColor: getTypeColor(type),
                    color: '#ffffff',
                    border: 'none'
                  }"
                  size="small"
                >
                  {{ getTypeDescription(type) }}
                </el-tag>
                <span class="type-count">{{ count }}</span>
              </div>
              <div class="type-progress">
                <el-progress
                  :percentage="getTypePercentage(count)"
                  :color="getTypeColor(type)"
                  :show-text="false"
                  :stroke-width="6"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 严重程度分布 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <h4>严重程度分布</h4>
              <el-button size="small" @click="refreshSeverityChart">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          <div class="severity-statistics">
            <div
              v-for="(count, severity) in severityDistribution"
              :key="severity"
              class="severity-item"
            >
              <div class="severity-info">
                <el-tag
                  :style="{
                    backgroundColor: getSeverityColor(severity),
                    color: '#ffffff',
                    border: 'none'
                  }"
                  size="small"
                >
                  {{ getSeverityDescription(severity) }}
                </el-tag>
                <span class="severity-count">{{ count }}</span>
              </div>
              <div class="severity-progress">
                <el-progress
                  :percentage="getSeverityPercentage(count)"
                  :color="getSeverityColor(severity)"
                  :show-text="false"
                  :stroke-width="6"
                />
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 匹配统计 -->
    <el-row :gutter="24" style="margin-top: 24px">
      <el-col :span="24">
        <el-card class="match-stats-card" shadow="hover">
          <template #header>
            <h4>匹配统计</h4>
          </template>
          <div class="match-stats">
            <div class="match-item">
              <div class="match-label">总匹配次数</div>
              <div class="match-value total-matches">
                {{ formatNumber(statistics?.totalMatches || 0) }}
              </div>
            </div>
            <div class="match-item">
              <div class="match-label">今日匹配次数</div>
              <div class="match-value today-matches">
                {{ formatNumber(statistics?.todayMatches || 0) }}
              </div>
            </div>
            <div class="match-item">
              <div class="match-label">平均匹配率</div>
              <div class="match-value avg-rate">
                {{ getAverageMatchRate() }}%
              </div>
            </div>
            <div class="match-item">
              <div class="match-label">活跃敏感词</div>
              <div class="match-value active-words">
                {{ getActiveWordsCount() }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import { Document, Check, Close, Plus, Refresh } from "@element-plus/icons-vue";
import {
  SensitiveWordType,
  SeverityLevel,
  SensitiveWordManagementUtils,
  getTypeDistributionApi,
  getSeverityDistributionApi,
  type SensitiveWordStatistics
} from "@/api/sensitive-word-management";

interface Props {
  /** 统计数据 */
  statistics: SensitiveWordStatistics | null;
  /** 加载状态 */
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
});

const emit = defineEmits<{
  refresh: [];
}>();

// 分布数据
const typeDistribution = ref<Record<string, number>>({});
const severityDistribution = ref<Record<string, number>>({});

// 获取类型颜色
const getTypeColor = (type: string) => {
  // 中文描述到枚举值的映射
  const typeMapping: Record<string, SensitiveWordType> = {
    脏话: SensitiveWordType.PROFANITY,
    政治敏感: SensitiveWordType.POLITICS,
    广告: SensitiveWordType.ADVERTISEMENT,
    暴力内容: SensitiveWordType.VIOLENCE,
    违法内容: SensitiveWordType.ILLEGAL,
    垃圾信息: SensitiveWordType.SPAM
  };

  // 如果是中文描述，转换为枚举值
  const enumType = typeMapping[type] || (type as SensitiveWordType);
  return SensitiveWordManagementUtils.getTypeColor(enumType);
};

// 获取类型描述
const getTypeDescription = (type: string) => {
  // 如果是中文描述，直接返回
  if (
    type.includes("脏话") ||
    type.includes("政治") ||
    type.includes("广告") ||
    type.includes("暴力") ||
    type.includes("违法") ||
    type.includes("垃圾")
  ) {
    return type;
  }
  // 否则按枚举值处理
  return SensitiveWordManagementUtils.getTypeDescription(
    type as SensitiveWordType
  );
};

// 获取严重程度颜色
const getSeverityColor = (severity: string | number) => {
  // 中文描述到枚举值的映射
  const severityMapping: Record<string, SeverityLevel> = {
    轻微: SeverityLevel.LIGHT,
    一般: SeverityLevel.NORMAL,
    中等: SeverityLevel.MEDIUM,
    严重: SeverityLevel.SERIOUS,
    极严重: SeverityLevel.CRITICAL
  };

  // 如果是中文描述，转换为枚举值
  let enumSeverity: SeverityLevel;
  if (typeof severity === "string") {
    enumSeverity = severityMapping[severity] || SeverityLevel.MEDIUM;
  } else {
    enumSeverity = severity as SeverityLevel;
  }

  return SensitiveWordManagementUtils.getSeverityColor(enumSeverity);
};

// 获取严重程度描述
const getSeverityDescription = (severity: string | number) => {
  // 如果是中文描述，直接返回
  if (
    typeof severity === "string" &&
    (severity.includes("轻微") ||
      severity.includes("一般") ||
      severity.includes("中等") ||
      severity.includes("严重"))
  ) {
    return severity;
  }

  // 否则按枚举值处理
  return SensitiveWordManagementUtils.getSeverityDescription(
    severity as SeverityLevel
  );
};

// 计算类型百分比
const getTypePercentage = (count: number) => {
  const total =
    Object.values(typeDistribution.value).reduce((sum, val) => sum + val, 0) ||
    1;
  return Math.round((count / total) * 100);
};

// 计算严重程度百分比
const getSeverityPercentage = (count: number) => {
  const total =
    Object.values(severityDistribution.value).reduce(
      (sum, val) => sum + val,
      0
    ) || 1;
  return Math.round((count / total) * 100);
};

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M";
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + "K";
  }
  return num.toString();
};

// 计算平均匹配率
const getAverageMatchRate = () => {
  if (!props.statistics || props.statistics.totalWords === 0) return "0.0";
  const rate = props.statistics.totalMatches / props.statistics.totalWords;
  return rate.toFixed(1);
};

// 计算活跃敏感词数量
const getActiveWordsCount = () => {
  if (!props.statistics) return 0;
  // 假设匹配次数大于0的为活跃敏感词
  return Math.min(
    props.statistics.enabledWords,
    Math.ceil(props.statistics.totalMatches / 10)
  );
};

// 加载类型分布数据
const loadTypeDistribution = async () => {
  try {
    const response = await getTypeDistributionApi();
    if (response.code === 200 && response.data) {
      typeDistribution.value = response.data;
    }
  } catch (error) {
    console.error("加载类型分布数据失败:", error);
  }
};

// 加载严重程度分布数据
const loadSeverityDistribution = async () => {
  try {
    const response = await getSeverityDistributionApi();
    if (response.code === 200 && response.data) {
      severityDistribution.value = response.data;
    }
  } catch (error) {
    console.error("加载严重程度分布数据失败:", error);
  }
};

// 刷新类型图表
const refreshTypeChart = () => {
  loadTypeDistribution();
  emit("refresh");
};

// 刷新严重程度图表
const refreshSeverityChart = () => {
  loadSeverityDistribution();
  emit("refresh");
};

// 组件挂载时加载分布数据
onMounted(() => {
  loadTypeDistribution();
  loadSeverityDistribution();
});
</script>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
  }

  .stat-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .stat-number {
    font-size: 24px;
  }

  .match-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }
}

@media (width <= 480px) {
  .match-stats {
    grid-template-columns: 1fr;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .stat-number,
  .type-count,
  .severity-count,
  .match-value {
    color: #e5e7eb;
  }

  .stat-label,
  .match-label {
    color: #9ca3af;
  }

  .match-item {
    background: #374151;
  }

  .match-item:hover {
    background: #4b5563;
  }
}

.statistics-cards {
  margin-bottom: 24px;
}

/* 统计卡片 */
.stat-card {
  height: 120px;
  cursor: pointer;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 8px 25px rgb(0 0 0 / 15%);
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 8px 0;
}

.stat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64px;
  height: 64px;
  margin-right: 16px;
  font-size: 48px;
  background: rgb(64 158 255 / 10%);
  border-radius: 12px;
}

.stat-info {
  display: flex;
  flex: 1;
  flex-direction: column;
  justify-content: center;
}

.stat-number {
  margin-bottom: 4px;
  font-size: 32px;
  font-weight: bold;
  line-height: 1;
  color: #333;
}

.stat-label {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

/* 不同类型卡片的颜色 */
.stat-card.total .stat-icon {
  color: #409eff;
  background: rgb(64 158 255 / 10%);
}

.stat-card.enabled .stat-icon {
  color: #67c23a;
  background: rgb(103 194 58 / 10%);
}

.stat-card.disabled .stat-icon {
  color: #909399;
  background: rgb(144 147 153 / 10%);
}

.stat-card.today .stat-icon {
  color: #e6a23c;
  background: rgb(230 162 60 / 10%);
}

/* 图表卡片 */
.chart-card {
  min-height: 300px;
  border-radius: 12px;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chart-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 类型统计 */
.type-statistics,
.severity-statistics {
  padding: 16px 0;
}

.type-item,
.severity-item {
  margin-bottom: 16px;
}

.type-item:last-child,
.severity-item:last-child {
  margin-bottom: 0;
}

.type-info,
.severity-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.type-count,
.severity-count {
  font-weight: 600;
  color: #333;
}

.type-progress,
.severity-progress {
  width: 100%;
}

/* 匹配统计 */
.match-stats-card {
  border-radius: 12px;
}

.match-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 24px;
  padding: 16px 0;
}

.match-item {
  padding: 16px;
  text-align: center;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.match-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.match-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.match-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.match-value.total-matches {
  color: #409eff;
}

.match-value.today-matches {
  color: #67c23a;
}

.match-value.avg-rate {
  color: #e6a23c;
}

.match-value.active-words {
  color: #f56c6c;
}
</style>
